﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Runtime.Serialization;

namespace CLibArtreve.security
{
    [Serializable]
    public class ArtrevePrincipal : IPrincipal, ISerializable
    {
        //CONNECTIONSTRING
        private string _connectionString;
        public string ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }
        private ArtreveIdentity identity;

        #region IPrincipal Members

        public IIdentity Identity
        {
            get { return identity; }
            set { identity = (ArtreveIdentity)value; }
        }

        public bool IsInRole(string role)
        {
            try
            {
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        public string[] GetRolesForUser(string username)
        {
            try
            {
                return null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }


        public string[] GetRoles(string userName)
        {
            try
            {
                return null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        #endregion
        //CONSTRUCTOR
        public ArtrevePrincipal(ArtreveIdentity cIndent, string connectionString)
        {
            this.Identity = cIndent;
            //CONNECTIONSTRING
            ConnectionString = connectionString;
        }
        //SERIALIZATION
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            //State will be CrossAppDomain for serialization induced by WebDev.WebServer
            if (context.State.Equals(StreamingContextStates.CrossAppDomain))
            {
                var identity = (ArtreveIdentity)this.Identity;

                var generic = new GenericPrincipal(identity, GetRoles(identity.Ticket.Name));

                info.SetType(generic.GetType());

                var serializableMembers = FormatterServices.GetSerializableMembers(generic.GetType());
                var serializableValues = FormatterServices.GetObjectData(generic, serializableMembers);

                for (int i = 0; i < serializableMembers.Length; i++)
                    info.AddValue(serializableMembers[i].Name, serializableValues[i]);
            }
            else
            {
                throw new InvalidOperationException("Serialization not supported");
            }
        }
    }
}
